package com.dp.util.upload;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.dp.fckeditor.UploadRule;
import com.dp.pub.SysProperty;
import com.dp.util.ImageCompress;
import com.dp.util.ImageScalee;
import com.dp.util.TimeStamp;

public class MutiFileUpload extends FileUploadBase {

    private Map<String, FileItem> files;// 保存上传的文件
    private Map<String, FileBase> fileNames;// 保存上传文件的名字
    
    private long filesSize = 0; // 所有文件的总大小
    private String curdate = (new java.text.SimpleDateFormat("yyyyMM")).format(new Date());

    public boolean isMultipart(HttpServletRequest request)
    {
        return ServletFileUpload.isMultipartContent(request);
    }
    
    public boolean parseRequest(HttpServletRequest request)
            throws UnsupportedEncodingException {

        files = new HashMap<String, FileItem>();
        fileNames = new HashMap<String, FileBase>();
        // Create a factory for disk-based file items

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(sizeThreshold);
        
        if (repository != null)
            factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setHeaderEncoding(encoding);

        //标记是新上传的图片还是替换旧文件
        boolean newPictureMark = true;
        String oldPictureFileName = "";
        try {
            List<FileItem> items = upload.parseRequest(request);
            String lastFilename = "";
            for (FileItem item : items) {
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String value = item.getString(encoding);
                    if(fieldName.equals("fileurl_app"))
                    {
                    	lastFilename = value;
                    }
                    if(fieldName.equals("spcode"))
                    {
                    	value = value.trim();
                    }
                    if(fieldName.equals("picfilename") && !value.equals(""))
                    {
                    	newPictureMark = false;
                    	oldPictureFileName = value;
                    }
                    parameters.put(fieldName, value);
                } else {
                    if (super.isValidFile(item)) {
                        continue;
                    }
                    //新文件
                    if(newPictureMark)
                    {
	                    String fieldName = item.getFieldName();
	                    String fieldNameBak = fieldName;
	                    if(fieldName.contains("pictureTag_"))
	                    {
	                    	fieldName = "pictureTag";
	                    }
	                    long size=item.getSize();
	                    String name = item.getName();
	                    String ext=name.substring(name.lastIndexOf(".")+1, name.length());
	                    String value="";
	                    String format = "";
	                    if(fileNames.get(fieldName)==null)
	                    {
	                    	value=TimeStamp.getSequence();
	                    	if(fieldName.contains("File("))
	                    	{
		                    	String type=fieldName.substring(0,fieldName.indexOf("File("));
		                    	if(type.equals("DistributeImage"))
		                    	{
		                    		type = "11";
		                    	}
		                    	else if(type.equals("PreviewImage"))
		                    	{
		                    		type = "12";
		                    	}
		                    	else if(type.equals("pic"))
		                    	{
		                    		type = "1";
		                    	}
		                    	else if(type.equals("audio"))
		                    	{
		                    		type = "2";
		                    	}
		                    	else if(type.equals("ebook"))
		                    	{
		                    		type = "4";
		                    	}
		                    	else if(type.equals("ebookclient"))
		                    	{
		                    		type = "5";
		                    	}
		                    	else if(type.equals("ebooksupport"))
		                    	{
		                    		type = "6";
		                    	}
		                    	else if(type.equals("ringtone"))
		                    	{
		                    		type = "7";
		                    	}
		                    	else if(type.equals("theme"))
		                    	{
		                    		type = "8";
		                    	}
		                    	else if(type.equals("video"))
		                    	{
		                    		type = "9";
		                    	}
		                    	else if(type.equals("software"))
		                    	{
		                    		type = "10";
		                    	}
		                    	else
		                    	{
		                    		type = "3";
		                    	}
		
		                    	String sname=name.replaceAll("\\\\", "/");
		                    	sname=sname.substring(sname.lastIndexOf("/")+1,sname.length());
		                    	if((lastFilename != null && !lastFilename.equals("")) && type.equals("3"))
		                    	{
		                    		value=lastFilename;
		                    	}
		                    	if(ext.compareToIgnoreCase("jpg") == 0 || ext.compareToIgnoreCase("jepg") == 0 || ext.compareToIgnoreCase("png") == 0
		                    			|| ext.compareToIgnoreCase("gif") == 0 || ext.compareToIgnoreCase("bmp") == 0)
		                        {
		                    		BufferedImage sourceImg = null;
		                        	try {
		    							sourceImg = javax.imageio.ImageIO.read(item.getInputStream());
		    							
		    						} catch (IOException e) {
		    							// TODO Auto-generated catch block
		    							e.printStackTrace();
		    						}
		    						String width = sourceImg.getWidth() + "";
									String height = sourceImg.getHeight() + "";
									format = format + "_" + width + "_" + height + "_" + ext.toLowerCase();
		                        }
		                    	else
		                    	{
		                    		format = format + ext.toLowerCase();
		                    	}
		                    	FileBase file=new FileBase(sname,value,type,ext.toLowerCase(),size,format);
		                        fileNames.put(fieldName, file);
		                    }
	                    	//add for picture content upload
	                    	else if(fieldName.equals("pictureTag"))
	                    	{
	                    		String picSize=fieldNameBak.substring(fieldNameBak.indexOf("_"));
	                    		String sname=name.replaceAll("\\\\", "/");
		                    	sname=sname.substring(sname.lastIndexOf("/")+1,sname.length());
		                    	//sname:old name,value:new name,type:1 because picture content
		                    	format = format + ext.toLowerCase();
		                    	value=value+picSize;
	                    		FileBase file=new FileBase(sname,value,"1",ext.toLowerCase(),size,format);
	                    		fileNames.put(fieldName, file);
	                    	}
	                    }
	                    else
	                    {
	                    	if(fieldName.equals("pictureTag"))
	                    	{
	                    		String picSize=fieldNameBak.substring(fieldNameBak.indexOf("_"));
		                    	FileBase file=(FileBase)fileNames.get(fieldName);
		                    	String lastPicFileName = file.getName();
		                    	value=lastPicFileName.substring(0,lastPicFileName.indexOf("_"))+picSize;
		                    	file.setSize(size);
	                    	}
	                    	else
	                    	{
		                    	FileBase file=(FileBase)fileNames.get(fieldName);
		                    	value=file.getName();
		                    	file.setSize(size);
	                    	}
	                    }
	                    files.put(value + "." + ext.toLowerCase(), item);
	                    filesSize += item.getSize();
	                }
                    //替换已有的图片文件
                    else
                    {
                    	String fieldName = item.getFieldName();
    		            String fieldNameBak = fieldName;
    		            if(fieldName.contains("pictureTag_"))
    		            {
    		            	fieldName = "pictureTag";
    		            }
    		            long size=item.getSize();
    		            String name = item.getName();
    		            String ext=name.substring(name.lastIndexOf(".")+1, name.length());
    		            String value=oldPictureFileName;
    		            String format = "";
    		            if(fileNames.get(fieldName)==null)
    		            {
//    		            	value=TimeStamp.getSequence();
    		            	//add for picture content upload
    		            	if(fieldName.equals("pictureTag"))
    		            	{
    		            		String picSize=fieldNameBak.substring(fieldNameBak.indexOf("_"));
    		            		String sname=name.replaceAll("\\\\", "/");
    		                	sname=sname.substring(sname.lastIndexOf("/")+1,sname.length());
    		                	//sname:old name,value:new name,type:1 because picture content
    		                	format = format + ext.toLowerCase();
    		                	value=value+picSize;
    		            		FileBase file=new FileBase(sname,value,"1",ext.toLowerCase(),size,format);
    		            		fileNames.put(fieldName, file);
    		            	}
    		            }
    		            else
    		            {
    		            	if(fieldName.equals("pictureTag"))
    		            	{
    		            		String picSize=fieldNameBak.substring(fieldNameBak.indexOf("_"));
    		                	FileBase file=(FileBase)fileNames.get(fieldName);
    		                	String lastPicFileName = file.getName();
    		                	value=lastPicFileName.substring(0,lastPicFileName.indexOf("_"))+picSize;
    		                	file.setSize(size);
    		            	}
    		            }
    		            files.put(value + "." + ext.toLowerCase(), item);
    		            filesSize += item.getSize();
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        return newPictureMark;
    }

    /** *//**
     * 上传文件, 调用该方法之前必须先调用 parseRequest(HttpServletRequest request)
     * @param parent 文件存储的目录
     * @throws Exception
     */
    public void upload(String spcodepath, String downloadpath,boolean statusNew) throws Exception {
        if (files.isEmpty())
            return;
        
        if (sizeMax > -1 && filesSize > super.sizeMax){
            String message = String.format("the request was rejected because its size (%1$s) exceeds the configured maximum (%2$s)", filesSize, super.sizeMax);
                    
            throw new SizeLimitExceededException(message, filesSize, super.sizeMax);
        }

        for (String key : files.keySet()) {
        	FileItem item = files.get(key);
        	String fieldName = item.getFieldName();
        	if(fieldName.contains("pictureTag_"))
        		fieldName = "pictureTag";
        	String type = fileNames.get(fieldName).getType();
        	String ext = fileNames.get(fieldName).getExt();
            String realPath = spcodepath + UploadRule.genFilePath(type);
            if(!statusNew){
            	realPath=spcodepath;
            }
            File uploadFilePath = new File(realPath);
            if(uploadFilePath.exists() == false) 
            {
            	uploadFilePath.mkdirs();
            }
            String filename = key.substring(0,key.lastIndexOf(".")+1);
            if(key.substring(key.lastIndexOf("."), key.length()).compareToIgnoreCase(".jad") == 0)
            {
            	String str = null;
            	BufferedReader br = new BufferedReader(new InputStreamReader(item.getInputStream()));
            	PrintWriter outFile = new PrintWriter(new File(realPath, key));
            	downloadpath = downloadpath + "&type=" + type + "&name=" + filename + "jar";
            	while ((str = br.readLine()) != null) 
            	{
            		if(str.startsWith("MIDlet-Jar-URL"))
            		{
            			str = "MIDlet-Jar-URL: " + downloadpath;            			
            		}
            		outFile.println(str);
            	}
            	br.close();
            	outFile.flush();
            	outFile.close();
            }
            else
            {
//            	if(type.equals("1"))
//            	{
//            		//xxxx_size.ext
//            		key = filename.replace(".", "")+fileNames.get(item.getFieldName()).getFormat()+"."+ext;
//            	}
            	File file = new File(realPath, key);
            	item.write(file);
            	if(type.equals("12"))
            	{
            		ImageCompress.ImageScale(realPath+"/", key, key.replaceAll("\\.", "_s."));
            		ImageScalee ims = new ImageScalee();
		        	String imageSizeStr = SysProperty.getPrep("news_imagesize");
		        	String imageFormat = SysProperty.getPrep("news_imageformat");
		        	if(imageFormat == null || imageFormat.equals(""))
						imageFormat = "jpg";
					String[] imageSizeAry = imageSizeStr.split(",");
					String[] imageFormatAry = imageFormat.split(",");
					for(String imageSize : imageSizeAry)
					{
						String screenWidHei = imageSize.split("@")[0];
						String picWidHei = imageSize.split("@")[1];
						int screenWidth = Integer.parseInt(screenWidHei.split("x")[0]);
						int screenHeight = Integer.parseInt(screenWidHei.split("x")[1]);
						int width = Integer.parseInt(picWidHei.split("x")[0]);
						int height = Integer.parseInt(picWidHei.split("x")[1]);
						if(imageFormatAry != null)
							for(String imageFormatStr : imageFormatAry)
								ims.compressPics(realPath+"/"+key, width, height, imageFormatStr,screenWidth,screenHeight);
						else
							ims.compressPics(realPath+"/"+key, width, height, imageFormat,screenWidth,screenHeight);
					
					}
            	}
            }
//            parameters.put(key, name);
        }
    }

    
    public void parseRequest(HttpServletRequest request,String picfilename) throws UnsupportedEncodingException {
		files = new HashMap<String, FileItem>();
		fileNames = new HashMap<String, FileBase>();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(sizeThreshold);
		if (repository != null)
		    factory.setRepository(repository);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding(encoding);
		
		try {
		    List<FileItem> items = upload.parseRequest(request);
		    String lastFilename = "";
		    for (FileItem item : items) {
		        if (item.isFormField()) {
		            String fieldName = item.getFieldName();
		            String value = item.getString(encoding);
		            if(fieldName.equals("fileurl_app"))
		            {
		            	lastFilename = value;
		            }
		            if(fieldName.equals("spcode"))
		            {
		            	value = value.trim();
		            }
		            parameters.put(fieldName, value);
		        } else {
		
		            if (super.isValidFile(item)) {
		                continue;
		            }
		            String fieldName = item.getFieldName();
		            String fieldNameBak = fieldName;
		            if(fieldName.contains("pictureTag_"))
		            {
		            	fieldName = "pictureTag";
		            }
		            long size=item.getSize();
		            String name = item.getName();
		            String ext=name.substring(name.lastIndexOf(".")+1, name.length());
		            ext = ext.toLowerCase();
		            String value=picfilename;
		            String format = "";
		            if(fileNames.get(fieldName)==null)
		            {
//		            	value=TimeStamp.getSequence();
		            	//add for picture content upload
		            	if(fieldName.equals("pictureTag"))
		            	{
		            		String picSize=fieldNameBak.substring(fieldNameBak.indexOf("_"));
		            		String sname=name.replaceAll("\\\\", "/");
		                	sname=sname.substring(sname.lastIndexOf("/")+1,sname.length());
		                	//sname:old name,value:new name,type:1 because picture content
		                	format = format + ext.toLowerCase();
		                	value=value+picSize;
		            		FileBase file=new FileBase(sname,value,"1",ext.toLowerCase(),size,format);
		            		fileNames.put(fieldName, file);
		            	}
		            }
		            else
		            {
		            	if(fieldName.equals("pictureTag"))
		            	{
		            		String picSize=fieldNameBak.substring(fieldNameBak.indexOf("_"));
		                	FileBase file=(FileBase)fileNames.get(fieldName);
		                	String lastPicFileName = file.getName();
		                	value=lastPicFileName.substring(0,lastPicFileName.indexOf("_"))+picSize;
		                	file.setSize(size);
		            	}
		            }
		            files.put(value + "." + ext.toLowerCase(), item);
		            filesSize += item.getSize();
		        }
		    }
				
				} catch (FileUploadException e) {
				    e.printStackTrace();
				}
				}
    
    
    public Map<String, FileItem> getFiles() {
        return files;
    }

    public Map<String, FileBase> getFileNames() {
        return fileNames;
    }    
}
